package com.fjwt.gz.coupon.gtpay;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.coupon.gtpay.demo.RSAUtilSegment;
import com.fjwt.gz.coupon.SendCouponBo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.Random;

import static com.fjwt.gz.coupon.gtpay.demo.MktSignUtil.createSign;
import static com.fjwt.gz.coupon.gtpay.demo.RSAUtilSegment.gt;

/**
 * 国通商户发券
 */
@Slf4j
@Service
public class GtpayCouponSendService {
    public static String gtKey = "Dl0AG8wdp45F";
    //TODO 注意： 上面记得封装一层，统一调用，通过不同通道调用不同的逻辑，


    // 定义日期时间格式
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");


    private static final Logger gtPayLogger = LoggerFactory.getLogger("gtPay");

    public JSONObject couponSend(SendCouponBo sendCouponBo) {
        String logPrefix = "【国通支付通道发券】";

        gtPayLogger.info("国通发券,sendCouponBo数据信息是：{}", JSONUtil.toJsonStr(sendCouponBo));

        if (Objects.isNull(sendCouponBo)) {
            throw new BizException("发券参数缺失！");
        }
        try {
            JSONObject bodys = new JSONObject();
            bodys.put("appid", sendCouponBo.getAppId());
            bodys.put("stock_id", sendCouponBo.getStockId());
            bodys.put("stock_creator_mchid", "1501970731");
            // 获取当前日期时间并格式化
            String timestamp = LocalDateTime.now().format(formatter);
            // 获取当前流水号，并在生成后自增
            Random random = new Random();
            int seq = 1000 + random.nextInt(9000);
            bodys.put("out_request_no", timestamp + seq);

            JSONObject jsonObject = this.grantCoupon(bodys, sendCouponBo.getOpenId());
            gtPayLogger.info("{},发券返回信息是：{}", logPrefix, JSONUtil.toJsonStr(jsonObject));
            return jsonObject;
        } catch (BizException e) {
            gtPayLogger.info("国通发券失败");
            throw e;
        } catch (Exception e) {
            gtPayLogger.info("国通发券失败");
            e.printStackTrace();
        }
        return null;
    }


    //国通发放卡券
    public JSONObject grantCoupon(JSONObject bodys, String openId) throws Exception {
        HttpResponse response = null;
        JSONObject json = new JSONObject();
        String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/users/" + openId + "/coupons";
        json.put("url", url);
        json.put("channelType", "D12");
        json.put("method", "POST");
        json.put("body", bodys);
        json.put("channelNo", "20250331095656498");
        gtPayLogger.info("请求参数：{}", json);
        String sign = createSign(com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(json)), gtKey);

        json.put("sign", sign);
        String encryptStr = new String(Base64.encodeBase64(RSAUtilSegment.encryptByPublicKey(String.valueOf(json).getBytes(), gt)));
        try {

            HttpRequest body = HttpRequest.post("https://mktcldxylmyxrhgw.postar.cn/h5font/public/api/restWxInterface")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .timeout(10000)
                    .body(encryptStr);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }

        if (response == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        JSONObject respData = JSONObject.parseObject(response.body());
        gtPayLogger.info("响应结果：{}", response);
        if (MapUtil.getStr(respData, "coupon_id") != null) {
            return respData;
        } else {
            if (MapUtil.getStr(respData, "message") != null) {
                throw new BizException(MapUtil.getStr(respData, "message"));
            } else {
                throw new BizException("网络波动请联系管理员");
            }
        }

    }

}
